package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"github.com/spf13/cast"
	"goravel/app/models"
)

type HistorytrackController struct {
	//Dependent services
}

func NewHistorytrackController() *HistorytrackController {
	return &HistorytrackController{
		//Inject services
	}
}

// Index 设备轨迹，支持按时间搜索，默认前三天至当前
// @Summary      设备轨迹查询
// @Description  设备轨迹查询
// @Tags         设备轨迹查询
// @Accept       json
// @Produce      json
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  id  query  int  false  "id"
// @Param  start_at  query  string  false  "start_at" "开始时间" example(2024-05-14 00:00:00)
// @Param  end_at  query  string  false  "end_at" "结束时间" example(2024-05-17 00:00:00)
// @Success 200 {string} json "{"code":"200", "data":"response data"}"
// @Router       /api/device/{id}/historytrack [get]
func (r *HistorytrackController) Index(ctx http.Context) http.Response {
	device_id := cast.ToUint(ctx.Request().Route("id"))
	//default_start_at 前三天
	//default_end_at 当前时间
	default_start_at := carbon.Now().SubDays(15).ToDateTimeString()
	default_end_at := carbon.Now().ToDateTimeString()

	start_at := ctx.Request().Query("start_at", default_start_at)
	end_at := ctx.Request().Query("end_at", default_end_at)
	historytracks := []models.Historytrack{}
	facades.Orm().Query().Model(&models.Historytrack{}).Where("device_id=?", device_id).With("Device").
		Where("location_at >=?", start_at).Where("location_at <=?", end_at).
		Order("location_at asc").Find(&historytracks)
	var model models.Historytrack
	distance := model.CalcDistance(historytracks)
	return ctx.Response().Success().Json(http.Json{
		"data":     historytracks,
		"distance": distance,
	})
}
